﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ScrumTracker.Models;
using System.Net;

namespace ScrumTracker.Controllers
{
    public class UsersController : Controller
    {
        //
        // GET: /Users/

        public ActionResult List()
        {
            var ctx = ScrumTrackerEntities.Instance;
            ViewData.Model = ctx.Users.Where(u => u.IsDeleted == false).OrderBy(u => u.FirstName).ToList();
            return View();
        }

        public ActionResult New()
        {
            return PartialView("_New", new User());
        }

        [HttpPost]
        public ActionResult Create(User model)
        {
            model.PasswordHash = "d41d8cd98f00b204e9800998ecf8427e"; //md5("")
            model.CreatedAt = DateTime.UtcNow;
            var ctx = ScrumTrackerEntities.Instance;
            if (ModelState.IsValid)
            {
                ctx.Users.AddObject(model);
                ctx.SaveChanges();
                Response.StatusCode = (int)HttpStatusCode.OK;
                Response.StatusDescription = "User successfully created";
            }
            else
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
            }
            return PartialView("_New", model);
        }

        public ActionResult Edit(int id)
        {
            var ctx = ScrumTrackerEntities.Instance;
            return PartialView("_Edit", ctx.Users.SingleOrDefault(u => u.UserId == id));
        }

        [HttpPost]
        public ActionResult Update(int id, User model)
        {
            var ctx = ScrumTrackerEntities.Instance;
            var entity = ctx.Users.SingleOrDefault(u => u.UserId == id);
            if (TryUpdateModel<User>(entity))
            {
                ctx.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);
                ctx.SaveChanges();
                Response.StatusCode = (int)HttpStatusCode.OK;
                Response.StatusDescription = "User successfully updated";
            }
            else
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
            }
            return PartialView("_Edit", entity);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            var ctx = ScrumTrackerEntities.Instance;
            var entity = ctx.Users.SingleOrDefault(u => u.UserId == id);
            entity.IsDeleted = true;
            ctx.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);
            ctx.SaveChanges();
            return Json(new { success = true });
        }
    }
}
